package com.june.pubsub;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;

import org.apache.activemq.ActiveMQConnectionFactory;

public class Subscriber {
	
	private static final String TOPIC_NAME = "testTopic";

	public static void main(String[] args) throws Exception {
		
		// 创建一个连接工厂 TopicConnectionFactory
		// user/password/url: admin/admin/tcp://localhost:61616
		TopicConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
				ActiveMQConnectionFactory.DEFAULT_USER, 
				ActiveMQConnectionFactory.DEFAULT_PASSWORD, 
				ActiveMQConnectionFactory.DEFAULT_BROKER_URL);
		// 从连接工厂得到一个连接 TopicConnection
		TopicConnection connection = connectionFactory.createTopicConnection();
		// 开启连接
		connection.start();

		// 通过连接来建立一个会话TopicSession
		TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
		// 创建主题
		Topic topic = session.createTopic(TOPIC_NAME);
		// 创建主题订阅者
		TopicSubscriber subscriber = session.createSubscriber(topic);
		System.out.println("订阅消息主题: " + TOPIC_NAME);
		// 添加消息监听器进行异步消息获取
		subscriber.setMessageListener(new MessageListener() {
			@Override
			public void onMessage(Message message) {
				if (!(message instanceof TextMessage)) {
					System.out.println("消息类型不正确，不予处理");
					return;
				}
				TextMessage textMessage = (TextMessage) message;
				if (textMessage != null) {
					try {
						System.out.println("订阅主题" + TOPIC_NAME + "接收到的消息: " + textMessage.getText());
					} catch (JMSException e) {
						e.printStackTrace();
					}
				}
			}
		});
		
		subscriber.close();
		session.close();
		connection.close();
	}

}
